package com.example.filter;

import com.example.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1.获取请求路径
        String requestURI = request.getRequestURI();
        // 2.判断请求路径是否包含 login
        if (requestURI.contains("/login") ) {
            log.info("登录请求");
            filterChain.doFilter(request, response);
            return;
        }
        //判断令牌是否存在
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            return;
        }
        try {
            // 解析token
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            response.setStatus(401);
            return;
        }
        filterChain.doFilter(request, response);
    }
}
